<template>
  <div class="div-input-wrapper">
    <div v-if="!isEdit" @click="handleClick" class="content-wrapper" :style="{ 'justify-content': columnConfig.align }">
      {{ row[column] }}
    </div>
    <el-input
      v-else
      v-model="row[column]"
      @blur="handleEmit"
      @change="handleChange"
      ref="inputRef"
      style="width: 100%"
    ></el-input>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, onBeforeUnmount, toRefs, nextTick } from 'vue';

const props = defineProps({
  row: {
    type: Object,
    default: () => {
      return {};
    },
  },
  column: {
    type: String,
    default: '',
  },
  columnConfig: {
    type: Object,
    default: () => {
      return {};
    },
  },
  eventBus: {
    type: Object,
    default: null,
  },
});

const { row, column, eventBus } = toRefs(props);
const isEdit = ref(false);
const ischange = ref(false);
const inputRef = ref();

const emit = defineEmits(['change']);

onMounted(() => {
  if (row.value.auto_flag) {
    handleClick();
  }
  // 监听关闭事件
  if (eventBus.value) {
    eventBus.value.$on('close-popovers', eventBus.value.handleClose);
  }
});

onBeforeUnmount(() => {
  // 组件销毁前移除监听
  if (eventBus.value) {
    eventBus.value.$off('close-popovers', eventBus.value.handleClose);
  }
});

function handleClick() {
  isEdit.value = true;
  nextTick(() => {
    inputRef.value.focus();
  });
}
function handleChange() {
  ischange.value = true;
}
function handleEmit() {
  isEdit.value = false;
  if (ischange.value || row.value.auto_flag) {
    ischange.value = false;
    emit('change', row.value, column.value, row.value[column.value]);
  }
}
function handleClose() {
  if (inputRef.value) {
    inputRef.value.blur();
  }
}
</script>

<style lang="scss" scoped>
.div-input-wrapper {
  min-height: 32px;
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  cursor: pointer;
  .content-wrapper {
    width: 100%;
    min-height: 32px;
    display: flex;
    align-items: center;
  }
}
</style>
